package com.shilan.dllo.wangyi.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.shilan.dllo.wangyi.R;
import com.shilan.dllo.wangyi.activity.HeadLineDetailActivity;
import com.shilan.dllo.wangyi.adpter.Headline_ad_Adpter;
import com.shilan.dllo.wangyi.adpter.Headline_recycleview_adpter;
import com.shilan.dllo.wangyi.clicklistenerininterface.OnMyClickListener;
import com.shilan.dllo.wangyi.entity.NewsEntity;
import com.shilan.dllo.wangyi.volley.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * Created by dllo on 15/10/23.
 */
public class HeadLineFragment extends Fragment implements OnMyClickListener {
    private RecyclerViewHeader header;

    private  ViewPager headviewPager; //广告栏
    private RecyclerView headrecyclerView;  //列表栏
    private Headline_ad_Adpter pagerAdapter; //定义广告栏内容适配器对象
    private Headline_recycleview_adpter recycleviewAdpter; //定义内容列表适配器对象
    private RequestQueue queue;


   private Handler handler;

    private  int currentItem = 0; //定义当前下标
    private  int maxItem = 1; //定义最大下标

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            maxItem = pagerAdapter.getCount();
            headviewPager.setCurrentItem((currentItem++) % maxItem);
            handler.postDelayed(runnable , 3000);
        }
    };
    public HeadLineFragment() {
    }

    /**
     * 加载布局
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //加载布局
        View v  = inflater.inflate(R.layout.activity_headline,container , false);

        return v;

    }

    /***
     *
     * 初始化控件
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化
        headviewPager= (ViewPager) view.findViewById(R.id.headViewPager);
        headrecyclerView = (RecyclerView) view.findViewById(R.id.headRecyclerView);

    }

    /***
     * 写逻辑
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recycleviewAdpter = new Headline_recycleview_adpter(getContext());
        //给recycleView设置布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),1);
        headrecyclerView.setLayoutManager(gridLayoutManager);
        headrecyclerView.setAdapter(recycleviewAdpter);
        recycleviewAdpter.setOnMyClickListener(this);

        queue = Volley.newRequestQueue(getContext());

        header = (RecyclerViewHeader) getActivity().findViewById(R.id.header);
        header.attachTo(headrecyclerView,true);

        pagerAdapter = new Headline_ad_Adpter(getFragmentManager());
        headviewPager.setAdapter(pagerAdapter);
        handler = new Handler();
        requestData();
    }

    public void requestData(){
        String url = "http://c.3g.163.com/nc/article/headline/T1348647853363/0-140.html";
        JsonObjectRequest request = new JsonObjectRequest(url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Gson gson = new Gson();
                        List<NewsEntity.T1348647853363Entity.AdsEntity> adslist = new ArrayList<>();
                        List<NewsEntity.T1348647853363Entity> list = new ArrayList<>();
                        if (response != null && response.has("T1348647853363")) {
                            try {
                                JSONArray array = response.getJSONArray("T1348647853363");
                                for (int i = 0; i < array.length(); i++) {
                                    String str1 = array.getString(i);
                                    NewsEntity.T1348647853363Entity entity = gson.fromJson(str1 ,
                                            NewsEntity.T1348647853363Entity.class);
                                    list.add(entity);
                                    Log.i("jjdfg" , list + "");
                                }
                                //添加list集合数据到适配器
                                recycleviewAdpter.addData(list);

                                JSONObject object = array.getJSONObject(0);
                                if (object != null && object.has("ads")) {
                                    JSONArray array1 = object.getJSONArray("ads");
                                    for (int i = 0; i < array1.length(); i++) {
                                        String str = array1.getString(i);
                                        NewsEntity.T1348647853363Entity.AdsEntity adsentity = gson.fromJson(str ,
                                                NewsEntity.T1348647853363Entity.AdsEntity.class);
                                        adslist.add(adsentity);
                                        Log.i("jdhjfkld" , adslist + "");
                                    }
                                    pagerAdapter.addData(adslist);
                                    handler.postDelayed(runnable, 3000);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }){

            @Override
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                //put后第一个参数看请求的接口请求头是否有要求 没要求就是默认下面这个
                map.put("Accept-Encoding", "");
                return map;
            }

        };

       queue.add(request);
    }

    @Override
    public void onClickListener(NewsEntity.T1348647853363Entity entity) {
        Intent intent = new Intent();
        intent.putExtra("url" , entity.getUrl());
        intent.setClass(getContext() , HeadLineDetailActivity.class);
        startActivity(intent);
    }
}
